package com.dbapp.imglib.crop;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.dbapp.imglib.inter.OnPicCropListener;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by Arirus on 2017/8/2.
 */

public class CropActivity extends AppCompatActivity {

  private static final int CROP_PHOTO = 930;
  private static OnPicCropListener sListener;

  private File file;

  public static void start(Context context, String picPath, OnPicCropListener listener) {
    sListener = listener;
    Intent starter = new Intent(context, CropActivity.class);
    starter.putExtra("path", picPath);
    context.startActivity(starter);
  }

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String picPath = getIntent().getStringExtra("path");
    //Uri uri = Uri.fromFile(new File(picPath));

    if (picPath == null || picPath.equals("")) {
      Toast.makeText(this, "地址无效", Toast.LENGTH_SHORT);
      this.finish();
      return;
    }

    file = new File(picPath);
    if (file == null) {
      Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT);
      this.finish();
      return;
    }

    Uri uri = null;

    if (Build.VERSION.SDK_INT >= 24) {
      //如果是7.0或以上，使用getUriForFile()获取文件的Uri

      String str_Pagkage_name = getAppProcessName(getApplicationContext());

      //imgUri = FileProvider.getUriForFile(this, "com.smart.safenotice" + ".fileprovider", imgFile);
      uri = FileProvider.getUriForFile(this, str_Pagkage_name + ".fileprovider", file);
    } else {
      uri = Uri.fromFile(file);
    }

    startPhotoZoom(uri);
  }

  public void startPhotoZoom(Uri uri) {
    Uri outputUri;
    file = new File(getExternalCacheDir(), "user-avatar_catch.jpg");
    // 如果存在就删了重新创建
    try {
      if (file.exists()) {
        file.delete();
      }
      file.createNewFile();
    } catch (IOException e) {
      e.printStackTrace();
    }
    outputUri = Uri.fromFile(file);

    //https://segmentfault.com/q/1010000007638333/a-1020000007719277
    //照片 截取输出的outputUri， 只能使用 Uri.fromFile，不能用FileProvider.getUriForFile

    Intent intent = new Intent("com.android.camera.action.CROP");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
      //添加这一句表示对目标应用临时授权该Uri所代表的文件
      intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", true);
    intent.putExtra("aspectX", 1);// 这两项为裁剪框的比例.
    intent.putExtra("aspectY", 1);// x:y=1:1
    //注意这里的输出的是上面的文件路径的Uri格式，这样在才能获取图片
    intent.putExtra("output", outputUri);
    intent.putExtra("outputFormat", "JPEG");// 返回格式
    startActivityForResult(intent, CROP_PHOTO);
  }

  /**
   * http://blog.csdn.net/true100/article/details/51028468
   * 获取当前应用程序的包名
   *
   * @param context 上下文对象
   * @return 返回包名
   */
  public static String getAppProcessName(Context context) {
    //当前应用pid
    int pid = android.os.Process.myPid();
    //任务管理类
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    //遍历所有应用
    List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
    for (ActivityManager.RunningAppProcessInfo info : infos) {
      if (info.pid == pid)//得到当前应用
      {
        return info.processName;//返回包名
      }
    }
    return "";
  }

  @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CROP_PHOTO && resultCode == RESULT_OK) {
      if (sListener != null) {
        sListener.OnCrop(file);
      }
    }
    finish();
  }
}
